import { isBoolean, isNumber, isString } from '../core/type';
import { jsonParse, jsonStringify } from '../core/json';
import { getStorageSync, setStorageSync, removeStorageSync } from '@tarojs/taro';
export const setStore = function (key: string, value: unknown) {
    try {
        let storeValue: unknown = '';
        if (isString(value) || isNumber(value)) {
            storeValue = value;
        }
        if (typeof value === 'object') {
            storeValue = jsonStringify(value);
        }
        if (isBoolean(value)) {
            storeValue = Boolean(value).toString();
        }
        setStorageSync(key, storeValue);
    } catch (error) {
        console.error('storage error', error);
        return;
    }
};

export const getStore = function (key: string) {
    if (typeof key !== 'string') {
        return;
    }
    try {
        const value = getStorageSync(key);

        if (value === 'true' || value === 'false') {
            return value === 'true';
        }
        if (isNumber(value)) {
            return value;
        }
        const regex = /^[\{\[].*[\}\]]$/;
        if (typeof value === 'string') {
            if (!regex.test(value)) {
                return value;
            }
            const obj = jsonParse(value);
            if (!obj) {
                return '';
            }
            return typeof obj === 'object' ? obj : value;
        }
        return '';
    } catch {
        return '';
    }
};

export const removeStore = function (ids: string | string[]) {
    try {
        if (!ids || (Array.isArray(ids) && !ids.length)) return;
        const keys = Array.isArray(ids) ? ids : [ids];
        keys.forEach((id: string) => {
            removeStorageSync(id);
        });
    } catch {
        console.error('清除数据缓存失败', ids);
    }
};
